package io.gitee.dtdage.app.boot.starter.web.security.utils;

import io.gitee.dtdage.app.boot.starter.web.security.context.Principal;
import io.gitee.dtdage.app.boot.starter.web.security.context.SecurityContext;
import io.gitee.dtdage.app.boot.starter.web.security.exception.AccessDeniedException;

/**
 * 权限工具类
 *
 * @author WFT
 * @since 2024/3/30
 */
public class SecurityUtil {

    /**
     * 私有化构造函数
     */
    private SecurityUtil() {

    }

    private final static ThreadLocal<SecurityContext> THREAD_LOCAL = new ThreadLocal<>();

    public static void clear() {
        THREAD_LOCAL.remove();
    }

    public static void set(SecurityContext context) {
        THREAD_LOCAL.set(context);
    }

    public static <T extends Principal> T get() {
        try {
            //noinspection unchecked
            return (T) getContext().getPrincipal();
        } catch (ClassCastException e) {
            throw new AccessDeniedException("当前接口不支持此类型用户访问!");
        }
    }

    public static SecurityContext getContext() {
        return THREAD_LOCAL.get();
    }

}
